import axios from 'axios';

// 根据环境决定API基础URL
// 开发环境使用代理，生产环境使用完整URL
const isDevelopment = import.meta.env.MODE === 'development';
let API_BASE_URL;

if (isDevelopment) {
  // 开发环境使用代理
  API_BASE_URL = '/api';
} else {
  // 生产环境使用环境变量或默认值
  const envUrl = import.meta.env.VITE_API_BASE_URL;
  if (envUrl && envUrl.trim() !== '') {
    API_BASE_URL = envUrl;
  } else {
    API_BASE_URL = 'http://localhost:8001';
  }
}

// 确保URL格式正确（移除末尾斜杠和空格）
API_BASE_URL = API_BASE_URL.trim().replace(/\/+$/, '');
console.log('API Base URL:', API_BASE_URL);

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

const apiService = {
  // Search materials
  async searchMaterials(query, limit = 10) {
    try {
      const response = await apiClient.get('/materials/search', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching materials:', error);
      throw error;
    }
  },

  // Get material details
  async getMaterialDetails(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}`);
      return response.data;
    } catch (error) {
      console.error('Error fetching material details:', error);
      throw error;
    }
  },

  // Get crystal structure
  async getCrystalStructure(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/structure`);
      return response.data;
    } catch (error) {
      console.error('Error fetching crystal structure:', error);
      throw error;
    }
  },

  // Get electronic structure
  async getElectronicStructure(materialId) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/electronic`);
      return response.data;
    } catch (error) {
      console.error('Error fetching electronic structure:', error);
      throw error;
    }
  },

  // Get example materials
  async getExampleMaterials() {
    try {
      const response = await apiClient.get('/examples');
      return response.data;
    } catch (error) {
      console.error('Error fetching examples:', error);
      throw error;
    }
  },

  // Get material papers
  async getMaterialPapers(materialId, limit = 100) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/papers`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error fetching material papers:', error);
      throw error;
    }
  },

  // Get material prices
  async getMaterialPrices(materialId, limit = 50) {
    try {
      const response = await apiClient.get(`/materials/${materialId}/prices`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error fetching material prices:', error);
      throw error;
    }
  },

  // Search papers directly
  async searchPapers(query, limit = 100) {
    try {
      const response = await apiClient.get('/search/baidu/papers', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching papers:', error);
      throw error;
    }
  },

  // Search prices directly
  async searchPrices(query, limit = 50) {
    try {
      const response = await apiClient.get('/search/baidu/prices', {
        params: { query, limit }
      });
      return response.data;
    } catch (error) {
      console.error('Error searching prices:', error);
      throw error;
    }
  },

  // Health check
  async healthCheck() {
    try {
      const response = await apiClient.get('/health');
      return response.data;
    } catch (error) {
      console.error('Health check failed:', error);
      throw error;
    }
  }
};

export default apiService;